/**
 * @desc 定义一些全局公用的方法
 * @author 大志
 * @update kyle
 * @date 2019-07-31
 * @inrto
 */

export default {
    Toast(msg) {
        uni.showToast({
            title: msg,
            icon: "none",
            duration: 2000,
        })
    },
    getMaxNum(num, addNum, addN) {
        let newNum = 0
        if (num / addNum > 1) {
            if (addN == 0) {
                newNum = num
            } else {
                newNum = num + (addNum - addN)
            }
        } else {
            newNum = addNum
        }
        return newNum
    },
    /**
     * 修改数量(新，以所选单位为基准)
     * @param {商品Object} item
     * @param {原有数量Number} num
     * @param {库存Number} stock
     * @param {类型Number} type (加，减，输入)
     * @param {最小值Number} min
     * @param {单位比例} unitRatio
     * @param {限购数量} limit
     * @param {增量} addNum
     */
    changeAmountNew(item, num, stock, type, min = 0, unitRatio = 1, limit = 0, addNum = 1) {
        addNum = !addNum ? 1 : addNum
        addNum = unitRatio == 1 ? addNum : 1
        addNum = Number(addNum)
        num = num
        let newNum = 0
        switch (type) {
            case -1:
                item.Amount = item.Amount - addNum
                if (item.Amount * unitRatio < min || item.Amount < 0) {
                    item.Amount = 0
                }
                break
            case 0:
                if (num <= 0) {
                    item.Amount = 0
                    break
                }
                // let addN = num%addNum
                newNum = num
                if (newNum * unitRatio < min) {
                    // min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    // addN = min%addNum
                    newNum = num
                    if (newNum > stock) {
                        newNum = 0
                        this.Toast("已达到最大库存")
                    } else {
                        newNum = min
                        this.Toast("最少购买" + min + "件")
                    }
                    item.Amount = newNum
                    break
                }

                if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0)) {
                    if (stock >= limit && limit > 0) {
                        newNum = parseInt(limit / unitRatio)
                        this.Toast("已达到限购数量")
                    } else {
                        newNum = parseInt(stock / unitRatio)
                        this.Toast("已达到最大库存")
                    }
                    if (unitRatio != 1 || addNum == 1) {
                        item.Amount = newNum
                    } else {
                        item.Amount = 0
                    }

                    break
                }
                item.Amount = newNum

                break
            case 1:
                newNum = Number(item.Amount) + Number(addNum)
                if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0)) {
                    if (stock >= limit && limit > 0) {
                        newNum = parseInt(limit / unitRatio)
                        this.Toast("已达到限购数量")
                    } else {
                        newNum = parseInt(stock / unitRatio)
                        this.Toast("已达到最大库存")
                    }
                    if (unitRatio != 1 || addNum == 1) {
                        item.Amount = newNum
                    }
                    break
                }
                if (newNum * unitRatio < min && unitRatio==1) {
                    // min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    // let addN = min%addNum
                    let newNum = min

                    if (newNum > stock) {
                        newNum = 0
                        this.Toast("已达到最大库存")
                    } else {
                        this.Toast("最少购买" + min + "件")
                    }
                    item.Amount = newNum
                    break
                }
                item.Amount = newNum
                break
        }
    },
    // changeAmountNew(item, num, stock, type, min = 0, unitRatio = 1, limit = 0, addNum = 1) {
    // 	addNum = !addNum ? 1 : addNum
    // 	addNum = unitRatio == 1 ?addNum:1
    // 	addNum = Number(addNum)
    // 	num = Number(num)
    // 	let newNum = 0
    //   switch (type) {
    //     case -1:
    //       item.Amount = Number(item.Amount) - addNum
    //       if (item.Amount * unitRatio < min || item.Amount<0) {
    //         item.Amount = 0
    //       }
    //       break
    //     case 0:

    // 		if(num==0){
    // 			item.Amount = 0
    // 			break
    // 		}
    // 		let addN = num%addNum
    // 		newNum = this.getMaxNum(num,addNum,addN)
    //       if (newNum * unitRatio < min) {
    // 			min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
    // 			addN = min%addNum
    // 			newNum = this.getMaxNum(min,addNum,addN)
    // 			if(newNum>stock){
    // 				newNum = 0
    // 				this.Toast("已达到最大库存")
    // 			}else{
    // 				this.Toast('最少购买' + newNum + '件')
    // 			}
    // 			item.Amount = newNum
    // 			break
    //       }

    // 		if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0)) {
    // 		  if (stock >= limit && limit > 0) {
    // 			newNum = parseInt(limit / unitRatio)
    // 			this.Toast('已达到限购数量')
    // 		  } else {
    // 			newNum = parseInt(stock / unitRatio)
    // 			this.Toast('已达到最大库存')
    // 		  }
    // 		  if(unitRatio != 1 || addNum==1){
    // 			  item.Amount = newNum
    // 		  }else{
    // 			  item.Amount =0
    // 		  }

    // 		  break
    // 		}
    // 		item.Amount = newNum

    //       break
    //     case 1:
    //       newNum = Number(item.Amount) + Number(addNum)
    //       if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0)) {
    //         if (stock >= limit && limit > 0) {
    //           newNum = parseInt(limit / unitRatio)
    //           this.Toast('已达到限购数量')
    //         } else {
    //           newNum = parseInt(stock / unitRatio)
    //           this.Toast('已达到最大库存')
    //         }
    // 		  if(unitRatio != 1 || addNum==1){
    // 		  	item.Amount = newNum
    // 		  }
    //         break
    //       }
    //       if (newNum * unitRatio < min) {
    // 			min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
    // 			let addN = min%addNum
    // 			let newNum = this.getMaxNum(min,addNum,addN)

    // 		  if(newNum>stock){
    // 		  	newNum = 0
    // 		  	this.Toast("已达到最大库存")
    // 		  }else{
    // 		  	this.Toast('最少购买' + newNum + '件')
    // 		  }
    // 		  item.Amount = newNum
    //         break
    //       }

    // 		item.Amount = newNum
    //       break
    //   }
    // },
    changeAmountclassNew(item, num, stock, type, min = 0, unitRatio = 1, limit = 0, addNum = 1, isDirect = false) {
        //沪材通
        addNum = !addNum ? 1 : addNum
        addNum = unitRatio == 1 ? addNum : 1
        addNum = Number(addNum)
        num = +num
        let newNum = 0
        switch (type) {
            case -1:
                if (stock <= 0 && !isDirect) {
                    return
                }
                item.Amount = item.Amount - addNum
                if (item.Amount * unitRatio < min && unitRatio==1) {
                    item.Amount = min
                    this.Toast("最少购买" + min + "件")
                }
                if (item.Amount <= 0) {
                    item.Amount = 1
                }
                if (String(item.Amount).indexOf(".") > -1) {
                    item.Amount = item.Amount.toFixed(1)
                }
                break
            case 0:
                if (stock <= 0 && !isDirect) {
                    return
                }
                if (num == 0) {
                    item.Amount = 1
                    break
                }
                // let addN = num%addNum
                newNum = num
                if (newNum * unitRatio < min && unitRatio==1) {
                    min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    // addN = min%addNum
                    newNum = min
                    if (newNum > stock && !isDirect) {
                        newNum = 1
                        this.Toast("已达到最大库存")
                    } else {
                        this.Toast("最少购买" + newNum + "件")
                    }
                    item.Amount = newNum
                    break
                }

                if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0) && !isDirect) {
                    if (stock >= limit && limit > 0) {
                        newNum = parseInt(limit / unitRatio)
                        this.Toast("已达到限购数量")
                    } else {
                        newNum = parseInt(stock / unitRatio)
                        this.Toast("已达到最大库存")
                    }
                    if (unitRatio != 1 || addNum == 1) {
                        item.Amount = newNum
                    } else {
                        item.Amount = 1
                    }

                    break
                }
                if (String(newNum).indexOf(".") > -1) {
                    item.Amount = newNum.toFixed(1)
                } else {
                    item.Amount = newNum
                }

                break
            case 1:
                if (stock <= 0 && !isDirect) {
                    return
                }
                newNum = Number(item.Amount) + Number(addNum)
                if (isDirect) {
                    item.Amount = newNum
                }
                if (newNum * unitRatio > stock || (newNum * unitRatio > limit && limit > 0)) {
                    if (!isDirect) {
                        if (stock >= limit && limit > 0) {
                            newNum = parseInt(limit / unitRatio)
                            this.Toast("已达到限购数量")
                        } else {
                            newNum = parseInt(stock / unitRatio)
                            this.Toast("已达到最大库存")
                        }
                    }
                    if (unitRatio != 1 || addNum == 1) {
                        item.Amount = newNum
                    }
                    break
                }
                if (newNum * unitRatio < min && unitRatio==1) {
                    min = parseInt(min / unitRatio) + (min % unitRatio > 0 ? 1 : 0)
                    let addN = min % addNum
                    let newNum = this.getMaxNum(min, addNum, addN)
                    if (newNum > stock && !isDirect) {
                        newNum = 0

                        item.Amount = newNum
                        this.Toast("已达到最大库存")
                    } else {
                        this.Toast("最少购买" + newNum + "件")
                    }
                    item.Amount = newNum

                    break
                }

                if (String(newNum).indexOf(".") > -1) {
                    item.Amount = newNum.toFixed(1)
                } else {

                    item.Amount = newNum
                }

                break
        }
    },
    /**
     * 将图片数据（string）转换为数组
     * @param {图片String} imgUrl
     */
    strToArr(imgUrl) {
        const arr = imgUrl.split(",")
        return arr
    },
    /** 获取星期几**/
    getCurrentweek() {
        const myDate = new Date()
        var days = myDate.getDay()
        switch (days) {
            case 1:
                days = "星期一"
                break
            case 2:
                days = "星期二"
                break
            case 3:
                days = "星期三"
                break
            case 4:
                days = "星期四"
                break
            case 5:
                days = "星期五"
                break
            case 6:
                days = "星期六"
                break
            case 0:
                days = "星期日"
                break
        }
        return days
    },

    /**
     * 时间格式化
     * @param {格式} format     yyyymmddHHMMSS 大小写要求严格
     * @param {需要格式化的时间} date
     */
    dateFomat(format, date) {
        const opt = {
            "y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString(), // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
        }

        for (var k in opt) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ? opt[k] : ("00" + opt[k]).substr(("" + opt[k]).length),
                )
            }
        }
        return format
    },
    /**
     * 时间区间选择
     */
    today() {
        const startDate = this.dateFomat("yyyy-mm-dd", new Date())
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return { startDate, endDate }
    },
    yesterday() {
        const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
        const startDate = this.dateFomat("yyyy-mm-dd", yesterday)
        const endDate = this.dateFomat("yyyy-mm-dd", yesterday)
        return { startDate, endDate }
    },
    thisWeek() {
        const weekday = new Date().getDay() || 7
        const thisweek1 = new Date(new Date().setDate(new Date().getDate() - weekday + 1))
        const startDate = this.dateFomat("yyyy-mm-dd", thisweek1)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return { startDate, endDate }
    },
    thisMonth() {
        const thismonth1 = new Date(new Date().setDate(1))
        const startDate = this.dateFomat("yyyy-mm-dd", thismonth1)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return { startDate, endDate }
    },
    thisYear() {
        const thisyear = new Date(new Date().getFullYear(), 0, 1)
        const startDate = this.dateFomat("yyyy-mm-dd", thisyear)
        const endDate = this.dateFomat("yyyy-mm-dd", new Date())
        return { startDate, endDate }
    },
    chooseMonth(date) {
        const monthStart = new Date(date.setDate(1))
        const y = this.dateFomat("yyyy", date)
        const m = this.dateFomat("m", date)
        const d = new Date(y, m, 0).getDate()
        const monthEnd = new Date(y, m - 1, d)
        const startDate = this.dateFomat("yyyy-mm-dd", monthStart)
        const endDate = this.dateFomat("yyyy-mm-dd", monthEnd)
        return { startDate, endDate }
    },
    // 当月（结束时间为下月1号）
    thisMonthS() {
        const thismonth1 = new Date(new Date().setDate(1))
        const startDate = this.dateFomat("yyyy-mm-dd", thismonth1)
        let y = thismonth1.getFullYear()
        let m = thismonth1.getMonth()
        if (m === 11) {
            m = -1
            y = y + 1
        }
        const _lastMonth = new Date(y, m + 1)
        const endDate = this.dateFomat("yyyy-mm-dd", _lastMonth)
        return { startDate, endDate }
    },
    // 结束时间为下月1号
    chooseMonthS(date) {
        const monthStart = new Date(date.setDate(1))
        let y = date.getFullYear()
        let m = date.getMonth()
        if (m === 11) {
            m = -1
            y = y + 1
        }
        const monthEnd = new Date(y, m + 1)
        const startDate = this.dateFomat("yyyy-mm-dd", monthStart)
        const endDate = this.dateFomat("yyyy-mm-dd", monthEnd)
        return { startDate, endDate }
    },

    // 获取上月年月(返回示例“2021-03”)
    lastMonth() {
        const nowDate = new Date()
        let y = nowDate.getFullYear()
        let m = nowDate.getMonth()
        if (m === 0) {
            m = 12
            y = y - 1
        }
        const _lastMonth = new Date(y, m - 1)
        const _data = this.dateFomat("yyyy-mm", _lastMonth)
        return _data
    },

    /** 规格描述字段整理（将“颜色_红色;尺码_大;”修改成“红色，大”）
     *  @param { 要修改的规格名称 } attrName
     */
    reSetAttr(attrName) {
        let newAttrName = ""
        if (attrName && attrName.indexOf(";") >= 0) {
            const _li = attrName.split(";")
            _li.forEach((item, index) => {
                if (item.indexOf("_") >= 0) {
                    newAttrName += item.split("_")[1] + "，"
                }
            })
        }
        if (newAttrName) {
            newAttrName = newAttrName.substring(0, newAttrName.length - 1)
        } else {
            newAttrName = attrName
        }
        return newAttrName
    },
    /*
            函数，加法函数，用来得到精确的加法结果
            说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
            参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数）
            调用：Calc.Add(arg1,arg2,d)
            返回值：两数相加的结果
            */
    add(arg1, arg2) {
        ; (arg1 = arg1.toString()), (arg2 = arg2.toString())
        var arg1Arr = arg1.split("."),
            arg2Arr = arg2.split("."),
            d1 = arg1Arr.length == 2 ? arg1Arr[1] : "",
            d2 = arg2Arr.length == 2 ? arg2Arr[1] : ""
        var maxLen = Math.max(d1.length, d2.length)
        var m = Math.pow(10, maxLen)
        var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen))
        var d = arguments[2]
        return typeof d === "number" ? Number(result.toFixed(d)) : result
    },
    /*
        函数：减法函数，用来得到精确的减法结果
        说明：函数返回较为精确的减法结果。
        参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数
        调用：Calc.Sub(arg1,arg2)
        返回值：两数相减的结果
        */
    sub(arg1, arg2) {
        return add(arg1, -Number(arg2), arguments[2])
    },
    /*
        函数：乘法函数，用来得到精确的乘法结果
        说明：函数返回较为精确的乘法结果。
        参数：arg1：第一个乘数；arg2第二个乘数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Mul(arg1,arg2)
        返回值：两数相乘的结果
        */
    mul(arg1, arg2) {
        var r1 = arg1.toString(),
            r2 = arg2.toString(),
            m,
            resultVal,
            d = arguments[2]
        m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0)
        resultVal = (Number(r1.replace(".", "")) * Number(r2.replace(".", ""))) / Math.pow(10, m)
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
    },
    /*
        函数：除法函数，用来得到精确的除法结果
        说明：函数返回较为精确的除法结果。
        参数：arg1：除数；arg2被除数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Div(arg1,arg2)
        返回值：arg1除于arg2的结果
        */
    div(arg1, arg2) {
        var r1 = arg1.toString(),
            r2 = arg2.toString(),
            m,
            resultVal,
            d = arguments[2]
        m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0)
        resultVal = (Number(r1.replace(".", "")) / Number(r2.replace(".", ""))) * Math.pow(10, m)
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
    },
}
